const MYSQL = require("../../sql/mysql");
const SQLName = "conversation";

const Config = require("../../config");
const DayJs = require("dayjs");
const Redis = require("../../redis");
/**
 * 会话添加消息 
 */
async function ConversationPushMessage(ConversationId, Data) {
    if (!ConversationId) {
        throw {
            code: 500, msg: "缺少会话ID"
        }
    }
    try {
        let RedisPath = `${ProjectName}:Messaging:Conversation:${ConversationId}:MessageList`
        await Redis.rPush(RedisPath, JSON.stringify(Data))
    } catch (error) {
        console.log(error);
        throw {
            code: 500, msg: "会话添加消息失败"
        }
    }
}

/**
 * 创建会话映射 (仅限单聊需要)
 */
async function CreateAloneContactMap() {

}
/**
 * 获取我的会话列表
 * @param {object} params 配置对象
 * @param {string} params.user 用户
 * @return {promise<{code:string,msg:string}>}
 */
async function GetConversationList(params = {}) {
    try {

        let {
            user,
            page = 1, // 当前页
            limit = 10, // 每页记录数量 
        } = params
        limit = limit < 1 ? (limit = 1) : limit;
        page = page < 1 ? (page = 1) : page;
        let Query = `
            SELECT *
            FROM ${SQLName}
            WHERE 
                (from_user = ${user} AND from_user_delete = 0) OR 
                (to_user = ${user} AND to_user_delete = 0)  AND state = 0
            LIMIT ${(page - 1) * limit + "," + page * limit}
        `;

        let mysqlResult = await MYSQL.promise().query(Query);
        let list = mysqlResult[0];

        // 获取数据总数 =====
        let totalResult = await MYSQL.promise().query(
            `
          SELECT Count(*) AS total FROM ${SQLName} WHERE state = 0
          `
        );
        let total = totalResult[0][0].total;
        let pages = Math.ceil(total / limit)
        return {
            code: 0, msg: "获取成功",
            data: {
                page, pages, list, limit
            }
        }
    } catch (err) {
        console.log(err);
        return {
            code: 500, msg: "操作失败,未知错误"
        }
    }

}
/**
 * 建立会话
 * @param {object} params 配置对象
 * @param {string} params.user 用户
 * @return {promise<{code:string,msg:string}>}
 */
async function StartConversation() { }
/**
 * 删除会话
 * @param {object} params 配置对象
 * @param {string} params.user 用户
 * @return {promise<{code:string,msg:string}>}
 */
async function DeleteConversation(params = {}) {
    try {
        let { id } = params
        await MYSQL.queryPromise(
            `UPDATE ${SQLName} SET state = 1 WHERE id = '${id}'`
        );
        return { code: 0, msg: "操作成功" };
    } catch (error) {
        return { code: 500, msg: "操作失败,未知错误" };
    }
}
/**
 * 会话设置置顶
 * @param {object} params 配置对象
 * @param {string} params.user 用户
 * @return {promise<{code:string,msg:string}>}
 */
async function SetConversationTop(user,ConversationId) {

    try {
		if(!user){
            throw {code:500,msg:"缺少user"}
        }else if(!ConversationId){
            throw {code:500,msg:"缺少ConversationId"}
        }

        let RedisPath = ``

        // 取出当前用户的会话配置

		let userConversationPath = ``
        let userConversationCurrentConfig = await Redis.get(userConversationPath)

        // 设置当前会话置顶
	} catch (error) {
		throw error 
	}

}
/**
 * 会话设置免打扰
 * @param {object} params 配置对象
 * @param {string} params.user 用户
 * @return {promise<{code:string,msg:string}>}
 */
async function DeleteConversation() { }
/**
 * 会话设置公告
 * @param {object} params 配置对象
 * @param {string} params.user 用户
 * @return {promise<{code:string,msg:string}>}
 */
async function DeleteConversation() { }
/**
 * 发送会话消息
 * @param {object} params 配置对象
 * @param {string} params.conversation_id 会话iD
 * @param {string} params.user 用户
 * @param {string} params.user 用户
 * @param {string} params.user 用户
 * @return {promise<{code:string,msg:string}>}
 */
async function PushConversationMessage(params = {}) {

    try {

        let {
            conversation_id,
            to_user, from_user,
            value_type, value,
        } = params

        // 当前时间
        let created_date = DayJs(Date.now()).valueOf();

        const SQLName = "conversation_message";

        // 将本次生成的消息记录存入数据库中
        await MYSQL.promise().query(`INSERT INTO ${SQLName} SET ?`, {
            conversation_id,
            to_user, from_user,
            value_type, value,
            created_date,
        });

        return {
            code: 0,
            msg: "操作成功",
        };

    } catch (err) {
        console.log(err);
        return {
            code: 500,
            msg: "操作失败,未知错误",
        };
    }

}
/**
 * 阅读会话
 * @param {object} params 配置对象
 * @param {string} params.user 用户
 * @return {promise<{code:string,msg:string}>}
 */
async function LookConversation(params = {}) {
    try {
        let sqlName = "conversation_message"
        let {
            page = 1,
            user, limit = 10,
            conversation_id
        } = params
        limit = limit < 1 ? (limit = 1) : limit;
        page = page < 1 ? (page = 1) : page;

        let listQuery = `
            SELECT * FROM ${sqlName} WHERE conversation_id = ${conversation_id} AND
            to_user = ${user} or from_user = ${user} AND state = 0
            ORDER BY created_date DESC
            LIMIT ${(page - 1) * limit + "," + page * limit}
        `
        let listQueryStatus = await MYSQL.promise().query(listQuery)
        let list = listQueryStatus[0];
        list.map(item => {
            if (item.to_user == user) {
                item.direction = 0
            }
            if (item.from_user == user) {
                item.direction = 1
            }
        })
            .sort((a, b) => a.created_date - b.created_date)



        // 获取数据总数 =====
        let totalResult = await MYSQL.promise().query(
            `
           SELECT Count(*) AS total FROM ${sqlName} WHERE conversation_id = ${conversation_id} AND
           to_user = ${user} or from_user = ${user} AND state = 0
        `
        );
        let total = totalResult[0][0].total;
        let pages = Math.ceil(total / limit)

        return {
            code: 0, msg: "操作成功", data: {
                list, pages, page, limit
            }
        };
    } catch (error) {
        console.log(error);
        return {
            code: 500,
            msg: "操作失败,未知错误",
        };
    }
}
module.exports = {
    GetConversationList,
    StartConversation,
    DeleteConversation,
    SetConversationTop,
    PushConversationMessage,
    LookConversation
}